<?php
	$start = microtime(true);
	define("QCMS",true);

	/* Where am I running?? */
	if(function_exists("realpath") && @realpath(dirname(__FILE__)))
	{
		define("BASEDIR",  realpath(dirname(__FILE__))."/");
		define("LIBDIR", BASEDIR."libraries/");
		define("CONDIR", BASEDIR."controllers/");
		define("VIEWDIR", BASEDIR."views/");
		define("HELPDIR", BASEDIR."helpers/");
	}
	else
	{
		error("Fatal Error: realpath function not available.",true);
	}
	
	require_once(HELPDIR."base.php");
	
	set_error_handler('error_handler',E_ALL^E_NOTICE);
	
	require_once(CONDIR."controller.php");
	
	/* Read configuration file */
	$CONFIG =& load_class("config");
	
	/* Initialise database */
	require_once(LIBDIR."DB/DB.interface.php");
	$db_driver = LIBDIR."DB/".$CONFIG->database.".db.php";
	if(file_exists($db_driver))
	{
		require_once($db_driver);
		$db_class = $CONFIG->database."DB";
	}
	else
	{
		error("Could not located the database driver for <strong>".$CONFIG->database."</strong>. Looked for ".$db_driver,true);
	}
	$DB = new $db_class("test.sqlite");
	
	/* Initialise libraries */
	$LIB =& load_class("library");
	$LIB->load(); 	// load function needs to be called after library class has fully instantiated
					// (ie. can not be called from the constructor) so libraries loaded by the library
					// class will have access to the library object through get_instance().
	
	/* Load helper functions */
	foreach ($CONFIG->helpers as $helper)
	{
		debug("loading helper: ".$helper);
		if(!@include_once(HELPDIR.$helper.".php"))
		{
			error("Could located helper ".$helper." in the helpers directory.",true);
		}
	}
	
	/* Process the request */
	if ( $LIB->url->segment(1) === false )
	{
		$controller = $CONFIG->default_controller;
		$method = "index";
	}
	else
	{
		$controller = $LIB->url->segment(1);
		if ( $LIB->url->segment(2) === false )
		{
			$method = "index";
		}
		else
		{
			$method = $LIB->url->segment(2);
		}
	}
	if (!@include_once(CONDIR.$controller.".php"))
	{
		error("Requested controller (".$controller.") could not be found.",true);
	}
	else
	{
		debug("Instantiating controller ".$controller.".");
		$CON = new $controller;
		if ( method_exists($CON,$method) )
		{
			$check = new ReflectionMethod($controller,$method);
			if ( $check->isPublic() )
			{
				$CON->$method();
			}
			else {
				debug("Requested method (".$method.") was found in controller (".$controller."), but is not public. 404 sent to browser.");
				error("Requested method (".$method.") could not be found within controller (".$controller.").",true);
			}
		}
		else
		{
			error("Requested method (".$method.") could not be found within controller (".$controller.").",true);
		}
	}
	$exec_time = (microtime(true)-$start);
	debug("Execution time: ".$exec_time." seconds.");
	
	
	print("<hr />");
	debug(true);
?>